/*
 * @Author: chengsl
 * @Date: 2021-12-21 14:33:18
 * @LastEditors: chengsl
 * @LastEditTime: 2023-05-10 11:23:40
 * @Description: request发请求疯装
 */
import axios from 'axios'
// import router from '@/router/routers'
import { ElNotification } from 'element-plus'
// eslint-disable-next-line no-unused-vars
import store from '../store'
import Config from '@/settings'
const { encode } = require('js-base64')
import { baseURL } from '@/settings'
// eslint-disable-next-line no-unused-vars
import { Encrypt, Decrypt } from '@/utils/AES' // 加密解密
// eslint-disable-next-line no-unused-vars
import Vue from 'vue'
// let resNoEncryption = false // 响应数据是否解密
// import Qs from 'qs'
// 创建axios实例
const service = axios.create({
  baseURL, // 测试环境
  timeout: Config.timeout // 请求超时时间
})
function errMsg(msg = '未知错误') {
  const replaceReg = new RegExp('///', 'gi')
  let message = '未知错误'
  if (msg) {
    message = `<div style="width:250px;text-align: initial;word-break: break-all">${msg
      .replace(replaceReg, '<br>')
      .replace("'", '<span style="color:red">"')
      .replace("'", '"</span>')
      .trim()}</div>`
  }

  ElNotification.error({
    message,
    dangerouslyUseHTMLString: true,
    duration: 2000
  })
}

/**
 * 将参数对象改造成url字符串返回
 * @param {*} obj
 * @returns str
 */
function requestBodyToUrl(obj) {
  let str = '?'
  const keys = Object.keys(obj)
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const value = obj[key]
    str = `${str}${key}=${value}${i === keys.length - 1 ? '' : '&'}`
  }
  return str
}
// request拦截器
service.interceptors.request.use(
  config => {
    try {
      // console.log('request', config)
      if (config.inUrl) { // 参数在URL里面
        const params = (typeof config.data === 'object') ? config.data
          : (typeof config.data === 'string')
            ? JSON.parse(config.data) : {}
        if (params && Object.keys(params).length) {
          config.url += requestBodyToUrl(params)
          config.data = undefined
        }
      }
      // console.log(`request---${config.url.split('/').reverse()[0]}---`, config.data)
    } catch (error) {
      console.log('error11--', error)
    }
    let TOKEN = ''
    if(window.__POWERED_BY_QIANKUN__) { // 用于测试，自行调整
      TOKEN = sessionStorage.getItem('udaam_token') || '6a5b1cd0-672f-4678-b7ad-51c67ae879f7'
    } else {
      TOKEN = localStorage.getItem('udaam_token') || '6a5b1cd0-672f-4678-b7ad-51c67ae879f7'
    }
     // localStorage.getItem('udaam_token') || store.state.global.udaam_token
    // const BUSINESS = sessionStorage.getItem('BUSINESS') // || store.state.global.BUSINESS || localStorage.getItem('BUSINESS')
    if (TOKEN) {
      config.headers.Authorization = 'Bearer ' + TOKEN
      // if (BUSINESS) {
      //   config.headers.BUSINESS = BUSINESS
      // }
    } else {
      config.headers.Authorization = 'Basic ' + encode('clientId:clent_secret')
    }
    config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json'
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      ElNotification.error({
        title: response.message
      })
      return Promise.reject('error')
    } else {
      // console.log(service, '-------serviceserviceservice')
      try {
        // console.log(`response---${response.config.url.split('/').reverse()[0]}---`, response.data)
      } catch (error) {
        //
      }
      // console.log(response.config.resNoEncryption, '响应数据是否需要解密')
      if ([61101, 61102].indexOf(response.data['code']) > -1) {
        ElNotification.warning({
          title: response.data['message']
        })
        return Promise.reject('error')
      }

      if (response.data.code === 200) { // TODO 和后端商量下 是否只有200代表接口成功
        return response.data
      } else {
        // Vue.prototype.$message.warning(response.data?.data?.message || response.data.message || '接口请求失败')
        return Promise.reject(response.data)
      }
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.data.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        ElNotification.error({
          title: '网络请求超时',
          duration: 2000
        })
        return Promise.reject(error)
      }
    }
    if (code) {
      if (code === 666) {
        ElNotification.error({
          title: '未经授权',
          duration: 5000
        })
      } else {
        ElNotification.error({
          title: '接口请求失败',
          duration: 2000
        })
      }
    } else {
      const errorCode = [1, 3, 4, 5, 6]
      console.log(error)
      if (errorCode.includes(error.response.data.code)) {
        errMsg(error.response.data.message)
      } else {
        ElNotification.error({
          title: '接口请求失败',
          duration: 2000
        })
      }
    }
    return Promise.reject(error)
  }
)
export default service
